package com.dietdroid;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class FoodInfoActivity extends Activity {
    public static CharacterStyle warningStyle = new ForegroundColorSpan(
                                                      0xFFFF0000);

    private FoodItem food;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.food_info_activity);
        Bundle extras = getIntent().getExtras();
        food = (FoodItem) extras.getSerializable("food");

        TextView name = (TextView) findViewById(R.id.foodinfoName);
        name.setText(food.getFood_name());

        ArrayList<String> allergens = DataStorage.getProfileData(this.getApplicationContext())
                .getAllergens();
        ArrayList<String> badIngredients = new ArrayList<String>();
        ;

        TextView ingredientView = (TextView) findViewById(R.id.foodinfoIngredients);
        SpannableStringBuilder ssb = new SpannableStringBuilder();
        for (String ingredient : food.getIngredients()) {
            ssb.append(ingredient);
            if (allergens.contains(ingredient)) {
                ssb.setSpan(warningStyle, ssb.length() - ingredient.length(),
                        ssb.length(), 0);
                badIngredients.add(ingredient);
            }
            ssb.append(", ");
        }
        if (ssb.length() != 0)
            ssb.delete(ssb.length() - 2, ssb.length());
        ingredientView.setText(ssb);

        ((TextView) findViewById(R.id.infoCalories)).setText(String.valueOf(food.getCalories()));
        ((TextView) findViewById(R.id.infoFat)).setText(String.valueOf(food.getTotal_fat()));
        ((TextView) findViewById(R.id.infoCholesterol)).setText(String.valueOf(food.getCholesterol()));
        ((TextView) findViewById(R.id.infoSodium)).setText(String.valueOf(food.getSodium()));
        ((TextView) findViewById(R.id.infoCarbohydrates)).setText(String.valueOf(food.getTotal_carbs()));
        ((TextView) findViewById(R.id.infoSugar)).setText(String.valueOf(food.getSugars()));//TODO
        ((TextView) findViewById(R.id.infoProtein)).setText(String.valueOf(food.getProtein()));
        ((TextView) findViewById(R.id.infoServing)).setText(String.valueOf(food.getServing_size()));

        
        boolean hasAllergens = !badIngredients.isEmpty();
        findViewById(R.id.allergenWarningText).setVisibility(
                hasAllergens ? View.VISIBLE : View.GONE);

        if (hasAllergens) {
            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(300);
            allergenAlert(badIngredients);
        }
        

        Button iAteThis = (Button) findViewById(R.id.iAteThisButton);
        iAteThis.setEnabled(!hasAllergens);
        iAteThis.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                addServing();
                Button iAteThis = (Button) findViewById(R.id.iAteThisButton);
                iAteThis.setText("Home");
                iAteThis.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                		Intent results = new Intent(FoodInfoActivity.this, MainActivity.class);
                		results.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    
                		startActivity(results);
                    }
                });
            }
        });

    }

    public void allergenAlert(List<String> allergens) {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Allergen Warning");
        alertDialog.setMessage("This food contains the following allergens: "
                + TextUtils.join(", ", allergens));
        alertDialog.setIcon(android.R.attr.alertDialogStyle);
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        alertDialog.show();
    }

    public void addServing() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setTitle("How many servings did you eat?");
        
        final CharSequence[] items = {"1", "1.5", "2", "2.5", "Custom"};
        
        alertDialog.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                if (item == items.length - 1) {
                    addServingCustom();
                } else {
                    CharSequence itemValue = items[item];
                    double num = Double.parseDouble(itemValue.toString());
                    addToHistory(num);
                }
            }
        });

        alertDialog.create().show();
    }
    
    public void addServingCustom() {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Add Serving To History");
        alertDialog.setMessage("How many servings did you eat?");
        
        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_CLASS_NUMBER);
        input.setText("3");
        alertDialog.setView(input);
        
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Add",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        double num;
                        try {
                           num = Double.parseDouble(input.getText().toString());
                        } catch(NumberFormatException nfe) {
                           num = 0;
                        }
                        addToHistory(num);
                    }
                });
        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        return;
                    }
                });
        alertDialog.show();
    }
    
    public void addToHistory(double servings) {
        HistoryData historyData =  DataStorage.getHistoryData(this.getApplicationContext());
        historyData.addHistoryForToday(food, servings);
        DataStorage.saveHistoryData(this.getApplicationContext(), historyData);
        Toast toast = Toast.makeText(this,
                String.format("%.2f servings of %s added to history.", servings, food.getFood_name()),
                Toast.LENGTH_SHORT);
        toast.show();
    }
}
